package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        //登陆操作，直接放行
        if (uri.contains("/login")) {
            log.info("登陆操作，直接放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = request.getHeader("token");
        if(token==null || token.isEmpty()){
            log.info("令牌为空，返回未授权状态");
            response.setStatus(401);
            return;
        }
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("令牌无效，返回未授权状态");
            response.setStatus(401);
            return;
        }
        log.info("令牌正确，放行");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
